package com.yootk.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * MDC拦截器
 */
@Slf4j
public class MDCInterceptor implements HandlerInterceptor {
    private final static String REQUEST_ID = "requestId";   // KEY名称

    // 每次请求前进行MDC绑定
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        String forward = request.getHeader("X-Forwarded-For");
        String clientIp = request.getRemoteAddr();
        String uuid = UUID.randomUUID().toString();     // 通过UUID生成requestId
        log.info("MDC操作记录开始：requestId = {}", uuid);
        log.info("requestId = {}, clientIp = {}, X-Forwarded-For = {}", uuid, clientIp, forward);
        MDC.put(REQUEST_ID, uuid);  // 保存MDC数据
        return true;
    }

    // 每次请求后进行MDC清除
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        String uuid = MDC.get(REQUEST_ID);
        log.info("MDC操作记录结束，requestId = {}", uuid);
        MDC.remove(REQUEST_ID);     // 删除MDC数据
    }
}
